using System;
using System.Data;
using Gtk;
using Npgsql;

public partial class MainWindow : Gtk.Window
{
	public MainWindow () : base(Gtk.WindowType.Toplevel)
	{
		Build ();
		string connectionString = "Server=localhost;Database=dbprueba;User Id=dbprueba;Password=sistemas";
		NpgsqlConnection dbConnection = new NpgsqlConnection(connectionString);
		
		dbConnection.Open();
		
		DataSet dataSet = new DataSet("dbPrueba");
		
		NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter("select * from articulo order by id", dbConnection);
		
		dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
		
		dataAdapter.Fill(dataSet);
		
		DataTable dataTable = dataSet.Tables[0];
		//modifico el primero		
		DataRow dataRow = dataTable.Rows[0];
		dataRow["nombre"] = "articulo " + DateTime.Now;
		dataRow["precio"] = 131;
		
		//elimino el último
		int ultimo = dataTable.Rows.Count - 1;
		DataRow deleteDataRow = dataTable.Rows[ultimo];
		deleteDataRow.Delete();
		
		//añado uno
		DataRow newDataRow = dataTable.NewRow();
		newDataRow["nombre"] = "articulo nuevo " + DateTime.Now;
		newDataRow["precio"] = 1.5m;
		dataTable.Rows.Add(newDataRow);
		
		new NpgsqlCommandBuilder(dataAdapter);
		
		dataAdapter.RowUpdating += delegate(object sender, NpgsqlRowUpdatingEventArgs e) {
			
			if (e.StatementType == StatementType.Insert) {
				string insertSql = string.Format("{0}; select currval('articulo_id_seq') as id", e.Command.CommandText);
				e.Command.CommandText = insertSql;
			};
			
			Console.WriteLine("RowUpdating Command.CommandText={0}", e.Command.CommandText);
		};
		
		dataAdapter.Update(dataSet.Tables[0]);

		showDataRow(newDataRow);		
		
		dbConnection.Close();		

//		dataSet.WriteXml("dataSet.xml", XmlWriteMode.WriteSchema);
		
//		DataSet dataSet = new DataSet();
//		dataSet.ReadXml("dataSet.xml");
//		showDataSet(dataSet);
	}
	
	private void showDataSet(DataSet dataSet)
	{
		Console.WriteLine("DataSet Name={0}", dataSet.DataSetName);
		foreach (DataTable dataTable in dataSet.Tables)
			showDataTable(dataTable);
	}
	
	private void showDataTable(DataTable dataTable)
	{
		Console.WriteLine("DataTable Name={0}", dataTable.TableName);
		foreach (DataRow dataRow in dataTable.Rows)
			showDataRow(dataRow);
	}
	
	private void showDataRow(DataRow dataRow)
	{
		foreach (DataColumn dataColumn in dataRow.Table.Columns)
			Console.WriteLine("{0}={1}", dataColumn.ColumnName, dataRow[dataColumn]);
	}
	                         

	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
}
